package com.kye.express.business.order_list.subfragment;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.Logger;
import com.kye.base.utils.DateUtils;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatFragment;
import com.kye.express.databinding.FragmentOrderListSignedBinding;
import com.kye.express.view.ToastManager;
import com.kye.lib.view.statuslayout.StatusLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;

import java.util.Calendar;
import java.util.Date;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * @author : Joe
 * @version : 1.0
 * @editor : Joe
 * @created : 29/12/2017
 * @updated : 29/12/2017
 * @description : <Description>
 * @update_reason : <UpdateReason>
 */
@Deprecated
public class OrderListSignedFragment extends BaseAppCompatFragment implements OrderListSignedContract.OrderListSignedView {

    private static final String DATE_PICKER_DIALOG = "DATE_PICKER_DIALOG";
    protected FragmentOrderListSignedBinding mDataBinding;
    protected OrderListSignedContract.OrderListSignedPresenter mPresenter;
    protected MultiTypeAdapter mAdapter;

    protected final int QUERY_DATE_FROM = 0;
    protected final int QUERY_DATE_TO = 1;

    public static OrderListSignedFragment newInstance() {
        Bundle args = new Bundle();
        OrderListSignedFragment fragment = new OrderListSignedFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_order_list_signed, container, false);
        initViews(view, savedInstanceState);
        return view;
    }

    private void initViews(View view, Bundle savedInstanceState) {
        mDataBinding = DataBindingUtil.bind(view);
        mDataBinding.setEnableQuery(false);
        mAdapter = new MultiTypeAdapter();
        mDataBinding.orderList.setLayoutManager(new LinearLayoutManager(getActivity()));
        mDataBinding.orderList.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
        mDataBinding.orderList.setItemAnimator(new DefaultItemAnimator());
        mDataBinding.orderList.setAdapter(mAdapter);
        mDataBinding.refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
//                presenter.loadMore();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
//                presenter.refresh();
            }
        });
        mDataBinding.setQueryDateFrom(new Date());
        mDataBinding.setQueryDateTo(new Date());
        mDataBinding.setEnableQuery(true);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mPresenter = new OrderListSignedContract.OrderListSignedPresenter();
        mPresenter.bind(this);
        mPresenter.onCreate(savedInstanceState);
        initEvents(savedInstanceState);
    }

    private void initEvents(Bundle savedInstanceState) {
        RxView.clicks(mDataBinding.llErrorServerCustom.btErrorServerRetry)
                .compose(new DebounceObservableTransformer<Object>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        mDataBinding.statusLayout.showLoadingView();
                    }
                });
        mDataBinding.statusLayout.setOnLoadingListener(new StatusLayout.OnLoadingListener() {
            @Override
            public void onLoading() {
//                presenter.refreshFirstTime();
            }
        });
        RxView.clicks(mDataBinding.tvDateFrom)
                .compose(new DebounceObservableTransformer<Object>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        showDateSelectDialog(QUERY_DATE_FROM);
                    }
                });
        RxView.clicks(mDataBinding.tvDateTo)
                .compose(new DebounceObservableTransformer<Object>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        showDateSelectDialog(QUERY_DATE_TO);
                    }
                });
        RxView.clicks(mDataBinding.btQuery)
                .compose(new DebounceObservableTransformer<Object>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {

                    }
                });
    }

    private void showDateSelectDialog(@IntRange(from = 0, to = 1) final int type) {
        int year;
        int monthOfYear;
        int dayOfMonth;
        Calendar calendar = Calendar.getInstance();
        if (type == QUERY_DATE_FROM) {
            if (mDataBinding.getQueryDateFrom() != null) {
                calendar.setTime(mDataBinding.getQueryDateFrom());
            }
        } else {
            if (mDataBinding.getQueryDateFrom() != null) {
                calendar.setTime(mDataBinding.getQueryDateTo());
            }
        }
        year = calendar.get(Calendar.YEAR);
        monthOfYear = calendar.get(Calendar.MONTH);
        dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog datePickerDialog = DatePickerDialog.newInstance(
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
                        Calendar calendar = Calendar.getInstance();
                        calendar.set(year, monthOfYear, dayOfMonth);
                        switch (type) {
                            case QUERY_DATE_FROM:
                                onSelectQueryDateFrom(calendar);
                                break;
                            case QUERY_DATE_TO:
                                onSelectQueryDateTo(calendar);
                                break;
                        }
                    }
                },
                year,
                monthOfYear,
                dayOfMonth
        );
        datePickerDialog.vibrate(true);
        datePickerDialog.setVersion(DatePickerDialog.Version.VERSION_1);
        datePickerDialog.showYearPickerFirst(true);
        datePickerDialog.show(getActivity().getFragmentManager(), DATE_PICKER_DIALOG);
    }

    private void onSelectQueryDateFrom(final Calendar calendarFrom) {
        Observable.just(mDataBinding.getQueryDateTo())
                .subscribeOn(Schedulers.io())
                .map(new Function<Date, Calendar>() {
                    @Override
                    public Calendar apply(Date date) throws Exception {
                        return DateUtils.dateToCalendar(date);
                    }
                })
                .map(new Function<Calendar, Boolean>() {
                    @Override
                    public Boolean apply(Calendar calendarTo) throws Exception {
                        return DateUtils.testLeftLessOrEqualToRight(calendarFrom, calendarTo);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        Logger.d("select date : " + aBoolean);
                        if (!aBoolean) {
                            ToastManager.show(getActivity(), "日期错误", Toast.LENGTH_SHORT);
                        } else {
                            mDataBinding.setQueryDateFrom(calendarFrom.getTime());
                        }
                    }
                });
    }

    private void onSelectQueryDateTo(final Calendar calendarTo) {
        Observable.just(mDataBinding.getQueryDateFrom())
                .subscribeOn(Schedulers.io())
                .map(new Function<Date, Calendar>() {
                    @Override
                    public Calendar apply(Date date) throws Exception {
                        return DateUtils.dateToCalendar(date);
                    }
                })
                .map(new Function<Calendar, Boolean>() {
                    @Override
                    public Boolean apply(Calendar calendarFrom) throws Exception {
                        return DateUtils.testLeftLessOrEqualToRight(calendarFrom, calendarTo);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        Logger.d("select date : " + aBoolean);
                        if (!aBoolean) {
                            ToastManager.show(getActivity(), "日期错误", Toast.LENGTH_SHORT);
                        } else {
                            mDataBinding.setQueryDateFrom(calendarTo.getTime());
                        }
                    }
                });
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    protected void initDataFirstTime(boolean isForceUpdate, @Nullable Bundle savedInstanceState) {
        mDataBinding.statusLayout.showLoadingView();
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        mPresenter.onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onDestroy() {
        mPresenter.unbind();
        super.onDestroy();
    }

    @Override
    public void onError() {

    }

    @Override
    public void onError(String msg) {

    }

    @Override
    public void onLoading() {

    }

    @Override
    public void onLoaded() {

    }

    @Override
    public FragmentOrderListSignedBinding getDataBinding() {
        return mDataBinding;
    }
}
